package storeSorting

import (
	"context"
	"errors"
	"fmt"
	"github.com/google/uuid"
	"github.com/shopspring/decimal"
	"gorm.io/gorm"
	"insighttracking/common/enum"
	"insighttracking/query/dao"
	"insighttracking/query/service"
	"net/http"

	"insighttracking/apps/sorting/internal/svc"
	"insighttracking/apps/sorting/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
	"os"
)

type ResetStoreSortingApiLogic struct {
	logx.Logger
	ctx     context.Context
	svcCtx  *svc.ServiceContext
	Request *http.Request
}

func NewResetStoreSortingApiLogic(ctx context.Context, svcCtx *svc.ServiceContext, request *http.Request) *ResetStoreSortingApiLogic {
	hostname, _ := os.Hostname()
	return &ResetStoreSortingApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:     ctx,
		svcCtx:  svcCtx,
		Request: request,
	}
}

func (l *ResetStoreSortingApiLogic) ResetStoreSortingApi(req *types.ResetStoreSortingReq) (resp string, err error) {
	// todo: add your logic here and delete this line
	detailEntities, err := service.StoreSortingDetailService.GetStoreSortingDetailBySpuIDApi(l.ctx, req.OrderId, req.SpuId)
	if err != nil || len(detailEntities) == 0 {
		return "操作成功", nil
	}
	storeSortingEntity, err := service.StoreSortingService.GetStoreSortingByIdApi(l.ctx, detailEntities[0].StoreSortingID)
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return "操作成功", nil
	}
	ordersEntity, err := service.OrdersService.GetByIdApi(l.ctx, storeSortingEntity.OrdersID)
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return "操作成功", nil
	}
	// 删除当前的数据并且减少总表入库数据
	tx := dao.Use(l.svcCtx.MysqlDb).Begin()
	computedCount := decimal.Zero
	computedAmount := decimal.Zero
	for _, item := range detailEntities {
		if err = service.StoreSortingDetailService.DeleteByIdApi(l.ctx, tx, item.ID); err != nil {
			if err = tx.Rollback(); err != nil {
				return "", err
			}
			return "", errors.New("取消失败")
		}
		computedCount = computedCount.Add(item.OutboundCount)
		computedAmount = computedAmount.Add(item.OutboundCount.Mul(item.SnapshotPrice))
	}
	totalCount := storeSortingEntity.TotalCount
	amount := storeSortingEntity.TotalAmount
	// 分拣商品要减少
	fmt.Println(totalCount.LessThanOrEqual(computedCount), "???", totalCount, "???", computedCount)
	if err = service.StoreSortingService.ModifyByIdApi(l.ctx, tx, storeSortingEntity.ID, totalCount.Sub(computedCount), amount.Sub(computedAmount)); err != nil {
		if err = tx.Rollback(); err != nil {
			return "", err
		}
		return "", errors.New("重置失败")
	}
	if totalCount.LessThanOrEqual(computedCount) {
		// 全部删除
		if err = service.StoreSortingService.DeleteByIdApi(l.ctx, tx, storeSortingEntity.ID); err != nil {
			if err = tx.Rollback(); err != nil {
				return "", err
			}
			return "", errors.New("重置失败")
		}
	}
	// 修改订单状态
	//if err = service.OrdersDetailService.ModifyStatusByIdListApi(l.ctx, tx, []int64{req.OrdersDetailId}, 0); err != nil {
	//	if err = tx.Rollback(); err != nil {
	//		return "", err
	//	}
	//	return "", errors.New("重置失败")
	//}
	// 判断订单状态
	if ordersEntity.Status == enum.OrdersAlreadyShippedEnum {
		if err = service.OrdersService.ModifyStatusByIdApi(l.ctx, tx, []int64{storeSortingEntity.OrdersID}, enum.OrdersCreateEnum); err != nil {
			if err = tx.Rollback(); err != nil {
				return "", err
			}
			return "", errors.New("取消失败")
		}
	}
	if err = tx.Commit(); err != nil {
		return "", errors.New("重置失败")
	}

	return "操作成功", nil
}
